import {observable, action, /*toJS*/} from 'mobx';
import {Toast,Tools,ListView,Modal,Bubble} from 'weaver-mobile';
import { Comment, Reply,Share } from 'weaver-mobile-page';
import {toJS} from 'mobx';
import * as Api from '../../api/doc';
import { ListViewPage } from 'weaver-mobile-page';
import DocConstant from '../../util';
import {downloadFile} from '../../util/Utils'
import ShareStore from '../docForm/ShareStore'


const getLabel = Tools.getLabel;

export default class DocStore {
  @observable id = '';
  @observable docInfo = {};
  @observable canRead = true;
  @observable isHaveDoc = '1'; 
  @observable praiseUserInfo = [];//文档点赞人员信息
  @observable docReplyInfo = [];//文档评论信息
  @observable loading = true;
  // @observable statusExpanded = false;// 文档状态信息是否展开
  @observable replyValue = '';
  @observable commentStore = new Comment.Store({
    getComment: this.getComment,
    getChild: this.getChildComment,
    operate: this.operateComment
  });
  commentLastId = 0;//最后一条评论的id，用于翻页
  path = "";//页面路径
  @observable typeKey = ''; //当前选中的tab的key（评论或者点赞）
  @observable docPraiseUsetDatasource = new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 !== row2,
  });
  @observable docReplyDatasource = new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 !== row2,
  });
  @observable replyStore = null;
  replyRef = null;
  @observable replyComment = null;
  @observable replyCommentParent = null;
  @observable commentReplyStoreMap = {};
  @observable singleAttachPath = '';
  @observable converting = true;
  @observable isConvertFileEnd = false;
  @observable attachsListDatasource = new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 !== row2, 
  });
  @observable MenuElliVisible = false;

  @observable currentNum = 0;
  @observable showfooter = true;
  pageY = 0;// 滑动时的位置
  pageStartX = 0;// 滑动时的位置
  pageStartY = 0;// 滑动开始时的位置，用于判断是否是点击事件
  @observable touchNum = 1; //当前点击屏幕的手指数量
  @observable isTimeoutPress = false; //是否长按了
  @observable isPraised = true; //判断当前点赞接口是否执行完毕，未执行完时不可点赞
  @observable praiseUserLoading = true; //点赞人员页面的加载
  @observable docInfoRefreshing = false; //下拉刷新状态
  
  @observable imgList = [];// 图片列表
  @observable imgInited = false;// 图片列表是否加载
  @observable imgVisible = false;// 是否查看图片
  @observable imgIndex = 0;// 查看图片顺序
  @observable logTab =[];// 日志tab
  @observable chooseLogTab = 0;// 当前选中的日志tab
  @observable chooseLogTabIndex = 0;// 当前选中的日志tab的索引
  @observable LogList;
  @observable openButtonVisible = false;
  @observable shareStore = null;
  @observable attachRowdata = {}; //记录下点击附件列表时，当前点击的附件的相关信息
  
  prevTitle = '';
  @observable otherMouldiframeParams = ""; //记录其他模块嵌套在iframe中带过来的参数
  // @observable otherMouldUrlParams = ""; //记录其他模块链接中带过来的参数
  @observable pagetype = ""; //是否展示共享页面
  @observable shareUserStore = null;
  @observable downloadParams = "";

  @observable secWmSet= {}; //当前文档所在目录的水印展示设置
  @observable isShowWater = true;//判断当前文档是否展示水印
  @observable isUsePoi = false;
  @observable docisLock = false;
  @observable attOperateVisible = false;
  @observable attOperateId = 0;
  @observable mainFileInfo={
    mainFileid:"",
    mainFileOnline:false,
    ficon:{},
  }
  
  @action
  init = (id, path,params) => {
    this.id = id;
    this.path = path;
    this.shareStore = new Share.Store({route: `${path || ''}/doc/${id}`});
    this.LogList = new ListViewPage.Store({route:`${path || ''}/doc/${id}/log`});// 日志列表
    this.typeKey = 'comment';
    this.loading = true;
    this.docInfo = {};
    this.isConvertFileEnd = false;
    this.MenuElliVisible = false;
    this.shareUserStore = new ShareStore({parent: this, path: this.path + `/doc/${id}`,saveBackFunc: this.addBack,id:this.id});
    let chagneTopTitle = (params && params.chagneTopTitle) ? params.chagneTopTitle : "true";
    let promise = this.getInfo().then(() => {
      this.loading = false;
      this.imgInited = false;
      if(this.canRead){
        
        let docInfo = toJS(this.docInfo)
        if(this.mainFileInfo.mainFileid && this.mainFileInfo.mainFileOnline && docInfo && docInfo.isContentEmpty && docInfo.canOpenSingleAttach){
        // if(docInfo && docInfo.isContentEmpty && Array.isArray(docInfo.docAttrs) && docInfo.docAttrs.length > 0 && docInfo.canOpenSingleAttach && docInfo.docAttrs[0].readOnLine==="1"){
          this.convertFile({fileid:this.mainFileInfo.mainFileid})
        }
        this.attachsListDatasource = this.attachsListDatasource.cloneWithRows(docInfo.docAttrs);
        if(chagneTopTitle!="false"){
          if (DocConstant.isApp()) {
            new Promise((resolve, reject) => {
              window.em.getTitle({'success':function (argument) {
                  resolve(argument);
                },'fail':function (argument) {
                  reject(argument);
                }}
              );
            }).then((res) => {
              this.prevTitle = res && res.result;
            }).catch(() => {
              this.prevTitle = getLabel(19874,'文档中心');
            });
            window.em.changeTitle({
              title: docInfo.docTitle
            });
          } else {
            this.prevTitle = window.document.title;
            window.document.title = docInfo.docTitle;
          }
        }
        
      }
    });
    this.replyStore = new Reply.Store({ getAttachList: this.getReplyAttachList });
    this.replyStore.doInit();

    return promise;
  }
  
  @action
  setAttOperate = (fileid,visible) =>{
  	this.attOperateVisible = visible;
  	this.attOperateId = fileid;
  }
  
 //切换当前tab（评论或点赞）
  changeTab = (tabkey) =>{
    this.typeKey = tabkey;
  }
  //设置详情
  setMenuElliVisible = (visible) =>{
    this.MenuElliVisible = visible;
  }
//获取所有的点赞用户
getPraiseUser = () => {
  return Api.getPraiseUser({docid: this.id}).then((result) => {
    this.praiseUserLoading = false;
    this.praiseUserInfo = [];
    this.praiseUserInfo = [...toJS(this.praiseUserInfo),...result.praiseList];
    this.docPraiseUsetDatasource = this.docPraiseUsetDatasource.cloneWithRows(toJS(this.praiseUserInfo));
  });
}
  //获取回复列表
  getReply = () =>{
    return Api.getReply({docid: this.id,lastid:-1}).then((result) => {
      this.docReplyInfo = [];
      this.docReplyInfo = [...toJS(this.docReplyInfo),...result.replyList];
      this.docReplyDatasource = this.docReplyDatasource.cloneWithRows(toJS(this.docReplyInfo));
    });
  }
  setDocLockStore = () =>{
        try{
            const {docStore} = this.props;
            let iframeList = document.getElementsByTagName("iframe");
			if(docStore.docisLock){
			  for(let index =0;index < iframeList.length; index++){
                let domNode = iframeList && iframeList[index].contentWindow.document;
                  if (!domNode) return;
                  if(domNode.body){
                   domNode.body.style.cssText += ';-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;user-select: none;unselectable:on;';
                   domNode.body.onselectstart = function () {return false};
                 }
			  }
			  if(document.body){
			    document.body.style.cssText += ';-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;user-select: none;unselectable:on;';
			    document.body.onselectstart = function () {return false};
			  }
			}
         } catch(e){
        // 防止跨域报错
         }
  }
  getInfo = (params) => {
    this.docInfoRefreshing = true;
    let from = "";
    from = (params && params.from) ? params.from :""
    return Api.getDocInfo({docid: this.id,from:from}).then((result) => {
      //拿到其他模块传过来的参数
      this.otherMouldiframeParams = DocConstant.getLocationUrlParams();
      this.reFreshTimeout = window.setTimeout(() => {
        this.reFreshTimeout = null;
        this.docInfoRefreshing = false;
      }, 1000)
      this.docInfo = result.docInfo;
      this.canRead = result.canReader || false;
      this.docisLock = result.docisLock || false;
      this.isHaveDoc = result.isHaveDoc || "1";
      this.mainFileInfo = result.mainFileInfo;
      if(this.docisLock){
      window.setTimeout(() => {
              this.setDocLockStore();
            },1);
      }
      if(this.canRead && this.isHaveDoc==='1'){
         this.secWmSet = result.secWmSet;
        if(result.secWmSet.isopenwater !== '1' || result.secWmSet.wmforview !== '1'){
          this.isShowWater = false;
          setTimeout(function(){
            if(window.waterMark){
              window.waterMark.destory();
            }
          },1);
        }
        let fileurl = ""
        let officeImagefileid = this.docInfo.officeImagefileid || "";
        let doctype = this.docInfo.doctype || "1";
        let doc_acc_isdownload = this.docInfo.doc_acc_isdownload || "1";
        let doc_acc_isalert_singleatt = this.docInfo.doc_acc_isalert_singleatt || "0";
        let singleAttachDownload = String(doctype) !== "1" && doc_acc_isdownload === "1" && officeImagefileid!=="" && this.docInfo.candownload;
        if(singleAttachDownload && doc_acc_isalert_singleatt==="1"){
          let attach = {};
          attach = this.docInfo.docAttrs.filter(item => {
            if(item.imagefileid === officeImagefileid){
              return item;
            }
          })
          if(toJS(attach[0]).readOnLine === "0"){
            fileurl = `/weaver/weaver.file.FileDownload?fileid=${officeImagefileid}&download=1&from_doc_mobile=1`;
            //嵌套在iframe中带过来的参数
            if(this.otherMouldiframeParams){
              fileurl = fileurl + `&${this.otherMouldiframeParams}`
            }
            this.alertDownload(fileurl,officeImagefileid,this.docInfo);
          }
        }
      }
    });
  }
  // 弹出下载的提示框
  alertDownload = (fileurl,officeImagefileid,docInfo) =>{
    docInfo.doc_acc_download_noalert === "1"
     ? Modal.alert(getLabel(24960,'提示信息'), getLabel(391350, "您查看的文档不能直接打开,是否下载查看?"), [
        { text: getLabel(31129, '取消')},
        { text: getLabel(826, '确定'), onPress: () => {
          downloadFile(fileurl,officeImagefileid);
          }
        },
      ])
    :downloadFile(fileurl,officeImagefileid);
  }
  praise = () => {
    Api.praiseDoc({docid: this.id, isPraise: this.docInfo.isPraise ? "1" : "0"}).then((result) => {
      this.isPraised = true;
      this.getInfo({from:'praise'});
    });
  }
  
  collect = () => {
    Api.collectDoc({docid: this.id, isCollute: this.docInfo.isCollute ? "1" : "0"}).then((result) => {
      this.getInfo({from:'collect'});
    });
  }
  
  setReplyValue = (v) =>{
    this.replyValue = v;
  }
  
  reply = (value) => {
    if(!value) {
      Toast.info(getLabel(388757, "请输入回复内容"));
      return;
    }
    let params = {
      documentid: this.id,
      content: value
    };
    
    Toast.loading("", 0);
    Api.replyDoc(params).then((result) => {
      Toast.hide();
      this.replyValue = '';
    }).catch(() => Toast.hide());
  }
  
  /**
   * 刷新评论列表
   */
  reloadComment = () => {
    this.commentLastId = '';
    this.commentStore.getDatas();
  }
  /**
   * 获得评论的分页数据
   * @returns {PromiseLike<T> | Promise<T> | *}
   */
  getComment = ({isFirstRequest} = {isFirstRequest: false}) => {
    let params = {docid: this.id};
    if (!isFirstRequest && this.commentLastId) {
      params.lastId = this.commentLastId;
    }
    return Api.getReply(params).then((result) => {
      if (Array.isArray(result.replyList) && result.replyList.length > 0) {
        this.commentLastId = result.replyList[result.replyList.length - 1].replyId;
      }
      return result;
    });
  }
  
  /**
   *
   * @param rowData
   * @returns {*}
   */
  getChildComment = ({data} = {}) => {
    return Api.getReply({docid: this.id, mainId: data.replyId});
  }
  operateComment = (params) => {
    const {type:{type} ,data, parent} = params;
    // 点赞
    if (type === 'fabulous') {
      return Api.praiseDoc({docid: this.id,replyid: data.replyId, isPraise: data.isPraise ?  1 : 0}).then((result) => {
        return {
          replyId: result.reply.replyId,
          reply: result.reply
        }
      });
    } else if (type === 'delete') {
      Modal.alert(getLabel(388758, '确认要删除吗？'), '', [
        { text: getLabel(31129, '取消')},
        {
          text: getLabel(33703, '确认'),
          onPress: () => {
            return Api.deleteReply({docid: this.id, replyid: data.replyId}).then((result) =>
              this.commentStore.doOperateReply({
                replyId: data.replyId,
                parentId: parent ? parent.replyId : '',
                reply: null
              })
            )
          }
        },
      ]);
    } else if (type === 'reply' || type === 'blog-comment') {
      if (!this.commentReplyStoreMap[data.replyId]) {
        let replyStore = new Reply.Store({ getAttachList: this.getReplyAttachList });
        replyStore.doInit();
        this.commentReplyStoreMap[data.replyId] = replyStore;
      }
      this.showReply(data, parent);
    }
  }
  
  saveComment = (content) => {
    let params = {
      documentid: this.id,
      content: content.text
    };
    if (this.replyComment) {
      params.replyid = this.replyComment.replyId;
    }
    const splitStr = '////~~weaversplit~~////';
    if (Array.isArray(content.imgList)) {
      params.imgFileids = content.imgList.map((img) => img.id).join();
      params.imgFilenames = content.imgList.map((img) => img.name).join(splitStr);
    }
    if (Array.isArray(content.attach.workflow)) {
      params.signworkflowids = content.attach.workflow.map((wf) => wf.id).join();
      params.signworkflownames = content.attach.workflow.map((wf) => wf.name).join(splitStr);
    }
    if (Array.isArray(content.attach.doc)) {
      params.signdocids = content.attach.doc.map((wf) => wf.id).join();
      params.signdocnames = content.attach.doc.map((wf) => wf.name).join(splitStr);
    }
    if (Array.isArray(content.attach.attach)) {
      params.fieldAnnexupload = content.attach.attach.map((item) => item.id).join();
      params.fieldAnnexuploadName = content.attach.attach.map((item) => item.name).join(splitStr);
    }
    // 不输入内容但有图片/流程等时会导致图片等加到上一条评论上，所以修改掉
    if (!params.content) {
      Toast.info(getLabel(388757, "请输入回复内容"), 1);
      return new Promise((rs, rj) => rj(getLabel(388757, "请输入回复内容")));
    }
    Toast.loading('loading', 0);
    return Api.replyDoc(params).then((result) => {
      if (this.replyComment) {
        this.commentStore.doOperateReply({
          replyId: result.reply.replyId,
          reply: result.reply,
        });
      } else {
        this.commentStore.getDatas();
        this.replyStore.doClear();
      }
      if(this.replyComment && this.replyComment.replyId){
        this.commentReplyStoreMap[this.replyComment.replyId].doClear();
      }
      this.docInfo.replyCount++;
      Toast.hide();
      this.hideReply();
    });
  }
  
  // toggleStatusExpanded = () => {
  //   this.statusExpanded = !this.statusExpanded;
  // }
  
  setReplyRef = (ref) => {
    this.replyRef = ref;
  }
  showReply = (reply, parent) => {
    const replyRef = this.replyRef;
    if (replyRef) {
      this.replyComment = reply;
      this.replyCommentParent = parent;
      replyRef.setVisible(true, () => {
        replyRef.getInputFocus();
      });
    }
  }
  hideReply = ()=>{
    let replyRef = this.replyRef;
    if (replyRef) {
      replyRef.setVisible(false, () => {
      
      });
    }
  }
  getReplyAttachList = () => {
    const attachList = [
      {
        key: 'workflow', // 字符串
        type: 'browser',
        config: {
          type: 152,
          isSingle: false,
          hasAdvanceSerach: true,
        },
        path: `${this.path || ''}/doc/${this.id}/comment`,
        iconType: 'flow',
        iconBgColor: '#61A8F5',
        text: getLabel(30045, '流程'),
      },
      {
        key: 'doc',
        type: 'browser',
        path: `${this.path || ''}/doc/${this.id}/comment`,
        config: {
          type: 37,
          isSingle: false,
        },
        iconType: 'file',
        iconBgColor: '#F3B04C',
        text: getLabel(22243, '文档'),
      },
      {
        key: 'attach',
        type: 'upload',
        path: `${this.path || ''}/doc/${this.id}/comment/replyAttach`,
        config: {
          multiSelection: true,
          maxUploadSize: this.docInfo.maxUploadSize,
          limitType: this.docInfo.limitType,
        },
        iconType: 'enclosure',
        iconBgColor: '#57D58F',
        text: getLabel(156, '附件'),
      },
    ];
    return new Promise((resolve,reject)=>resolve({attachList}));
  }
  
  //附件转换
  @action
  convertFile = (params) =>{
    Api.isPicture({fileid:params.fileid}).then((res)=>{
      const isiPhone = Tools.mobileDetect().is('iPhone');
      let ispic = res.ispic,url=`/weaver/weaver.file.FileDownload`;
      if(ispic==="0"){
          Toast.loading(getLabel(390467,'正在转换中...'),0);
      }
      Api.convertFile({convertFile:'html',fileid:params.fileid}).then((result)=>{
        ispic ==="0" && Toast.hide();
        if("system"===result.convert){
          this.isUsePoi = true;
          let convertId = "",status=0;
          convertId = result.convertId;
          status = result.status;
          if(status===1){
              
              this.isConvertFileSuccess = true;
              if(isiPhone){
                url = url + `?fileid=${params.fileid}&download=1`
              }else{
                url = url + `?fileid=${convertId}`
              }
              if(this.otherMouldiframeParams){
                url = url + `&${this.otherMouldiframeParams}`
              }
              this.singleAttachPath = url;
          }else{
              this.isConvertFileSuccess = false;
              this.convertMessage = "转换失败";
          }
      }else{
        if(result.result===0){
          let attachpath = result.data?(result.data[0].path?result.data[0].path:result.data[0]):'';
          let flag = attachpath.indexOf("spa/document/index2mobile");
          if(flag<0){
              flag = attachpath.indexOf("docs/pdfview/web/pdfViewer");
          }
          attachpath = (flag>0 && this.otherMouldiframeParams)? (attachpath + (attachpath.indexOf('?')>0 ? '&' : '?')+this.otherMouldiframeParams):attachpath;
          this.singleAttachPath = attachpath;
        }else{
          Toast.fail(result.message,1);
        }
      }
        this.isConvertFileEnd = true;
      });
    }) 
  }
  setImgList = (imgList) => {
    this.imgList = imgList;
    this.imgInited = true;
  }
  
  openImg = (index) => {
    this.imgIndex = index;
    this.imgVisible = true;
  }
  
  closeImg = () => {
    this.imgVisible = false;
  }
  
  updateImg = (index, newProps) => {
    let imgList = toJS(this.imgList);
    if (index < 0 || index > imgList.length) {
      return;
    }
    imgList[index] = {...imgList[index], ...newProps};
    this.imgList = [...imgList];
  }
  //获取日志的tab信息
  getLogTabInfo = () =>{
    Api.getLogTabInfo({docid:this.id}).then((result)=>{
      this.logTab = result.groupinfo;
    })
  }
  //切换log页面的tab
  changeLogtab = (tab,path) =>{
    this.chooseLogTab = tab.viewcondition;
    this.logTab.map((val,index) => {
      if(val.viewcondition === tab.viewcondition){
        this.chooseLogTabIndex = index;
      }
      return val;
    })
    this.LogList = new ListViewPage.Store({route:`${path || ''}/doc/${this.id}/log`});// 日志列表
    this.getLogListData(tab.viewcondition);
  }
  
  //获取日志信息
  getLogListData = (viewcondition) =>{
    this.LogList.clearData();
    Api.getLogList({docid:this.id,viewcondition,ismobile:'1'}).then((result)=>{
      if(this.chooseLogTab !== viewcondition){
        return ;
      }
      const{datas:dataKey} = result;
      this.LogList.getData({dataKey},(dataRes) =>{
        if(this.chooseLogTab !== viewcondition){
          dataRes.status = false;
        }
      });
    })
    this.LogList.updateDataSource();    
  }
  
  setOpenButtonVisible = (v) => {
    this.openButtonVisible = v;
  }

  //柳州下载接口
  downloadFile = (imagefileid) =>{
    Api.downloadfile({fileid:imagefileid,download:'1'}).then((result)=>{

    })
  }
  //提交草稿状态的文档
  dosubmit = (params) =>{
    Api.dosubmit(params).then((result)=>{
      if(result.blnOsp==="1"){
        this.pagetype = 'share';
      }
    })
  }

  addBack = ({id, history}) => {
    // this.getFirstPage();
    history.go(-1);
  }

  getDownloadParams = (params) =>{
    return Api.getDownloadParams(params);
  }

  updateBizStateForDoc = (params) => {
    return Api.updateBizStateForDoc(params);
  }

  deleteDoc = (params,netxprop=null) =>{
    return Api.deleteWarm().then(result=>{
      Modal.alert(getLabel(24960,'提示信息'), (result.title + (result.subTitle?"("+result.subTitle+")":"")), [
        { text: getLabel(31129, '取消')},
        { text: getLabel(826, '确定'), onPress: () => {
          Api.deleteDoc(params).then(data=>{
            if(data.status === 1){
             Bubble.success(data.msg);
             if(netxprop!=null){
               netxprop.history.go(-1);
             }
            }else{
             Bubble.error(data.msg);
            }
          })
         }
        },
      ])
    })
     
  }
}